using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace GenerativeAgents.Core
{
    /// <summary>
    /// 计划系统
    /// 负责智能体的行为规划、任务分解和执行控制
    /// </summary>
    public class PlanningSystem : MonoBehaviour
    {
        [Header("计划配置")]
        [SerializeField] private int maxDailyPlans = 10;
        [SerializeField] private int maxActivePlans = 3;
        [SerializeField] private float planningInterval = 60f; // 秒
        [SerializeField] private bool enablePlanningLogging = false;
        
        [Header("计划优先级设置")]
        [SerializeField] private float urgentPriorityWeight = 2f;
        [SerializeField] private float importantPriorityWeight = 1.5f;
        [SerializeField] private float defaultPriorityWeight = 1f;
        
        // 组件引用
        private MemorySystem memorySystem;
        private RetrievalEngine retrievalEngine;
        private ILanguageModel languageModel;
        private ActionPlanner actionPlanner;
        private PathFinder pathFinder;
        
        // 计划状态
        private List<PlanItem> currentPlans;
        private List<PlanItem> dailySchedule;
        private DateTime lastPlanningTime;
        private bool isPlanningInProgress = false;
        
        // 计划统计
        private int totalPlansCreated = 0;
        private int totalPlansCompleted = 0;
        private int totalPlansCancelled = 0;
        private Dictionary<string, int> planTypeStats;
        
        // 事件
        public event System.Action<PlanItem> OnPlanCreated;
        public event System.Action<PlanItem> OnPlanStarted;
        public event System.Action<PlanItem> OnPlanCompleted;
        public event System.Action<PlanItem> OnPlanCancelled;
        public event System.Action<List<PlanItem>> OnDailyScheduleUpdated;
        
        private void Awake()
        {
            InitializePlanningSystem();
        }
        
        private void Start()
        {
            StartPlanningLoop();
        }
        
        private void Update()
        {
            UpdatePlanExecution();
            CheckPlanningTrigger();
        }
        
        /// <summary>
        /// 初始化计划系统
        /// </summary>
        private void InitializePlanningSystem()
        {
            // 获取组件引用
            memorySystem = GetComponent<MemorySystem>();
            retrievalEngine = GetComponent<RetrievalEngine>();
            languageModel = GetComponent<ILanguageModel>();
            
            // 创建子组件
            actionPlanner = new ActionPlanner();
            pathFinder = new PathFinder();
            
            // 初始化数据结构
            currentPlans = new List<PlanItem>();
            dailySchedule = new List<PlanItem>();
            planTypeStats = new Dictionary<string, int>();
            
            lastPlanningTime = DateTime.Now;
            
            if (enablePlanningLogging)
            {
                Debug.Log("[PlanningSystem] Planning system initialized");
            }
        }
        
        /// <summary>
        /// 开始计划循环
        /// </summary>
        private void StartPlanningLoop()
        {
            // 创建初始日程安排
            GenerateInitialDailySchedule();
        }
        
        /// <summary>
        /// 更新计划执行
        /// </summary>
        private void UpdatePlanExecution()
        {
            try
            {
                // 检查当前计划的执行状态
                var plansToUpdate = new List<PlanItem>(currentPlans);
                
                foreach (var plan in plansToUpdate)
                {
                    UpdatePlanStatus(plan);
                }
                
                // 启动新的计划
                StartQueuedPlans();
            }
            catch (Exception ex)
            {
                Debug.LogError($"[PlanningSystem] Error updating plan execution: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 检查计划触发器
        /// </summary>
        private void CheckPlanningTrigger()
        {
            if (isPlanningInProgress) return;
            
            // 定期重新规划
            if ((DateTime.Now - lastPlanningTime).TotalSeconds >= planningInterval)
            {
                TriggerReplanning("periodic");
            }
            
            // 检查是否需要紧急重新规划
            var activePlans = currentPlans.Where(p => p.status == PlanStatus.InProgress).ToList();
            if (activePlans.Count == 0 && currentPlans.Count > 0)
            {
                TriggerReplanning("no_active_plans");
            }
        }
        
        /// <summary>
        /// 触发重新规划
        /// </summary>
        public void TriggerReplanning(string reason, ScratchMemory scratchMemory = null)
        {
            if (isPlanningInProgress) return;
            
            try
            {
                isPlanningInProgress = true;
                lastPlanningTime = DateTime.Now;
                
                if (enablePlanningLogging)
                {
                    Debug.Log($"[PlanningSystem] Triggered replanning due to: {reason}");
                }
                
                // 执行重新规划
                PerformReplanning(scratchMemory);
            }
            catch (Exception ex)
            {
                Debug.LogError($"[PlanningSystem] Error during replanning: {ex.Message}");
            }
            finally
            {
                isPlanningInProgress = false;
            }
        }
        
        /// <summary>
        /// 执行重新规划
        /// </summary>
        private void PerformReplanning(ScratchMemory scratchMemory)
        {
            try
            {
                // 1. 评估当前计划状态
                EvaluateCurrentPlans();
                
                // 2. 收集规划相关的记忆
                var planningMemories = CollectPlanningMemories(scratchMemory);
                
                // 3. 生成新的计划
                var newPlans = GenerateNewPlans(planningMemories, scratchMemory);
                
                // 4. 整合新计划到当前计划列表
                IntegrateNewPlans(newPlans);
                
                // 5. 优化计划顺序
                OptimizePlanOrder();
                
                if (enablePlanningLogging)
                {
                    Debug.Log($"[PlanningSystem] Replanning completed. Active plans: {currentPlans.Count}");
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"[PlanningSystem] Error performing replanning: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 生成新计划
        /// </summary>
        private List<PlanItem> GenerateNewPlans(List<MemoryNode> planningMemories, ScratchMemory scratchMemory)
        {
            var newPlans = new List<PlanItem>();
            
            try
            {
                // 基于目标生成计划
                if (scratchMemory != null && scratchMemory.goals.Count > 0)
                {
                    foreach (var goal in scratchMemory.goals.Take(3))
                    {
                        var goalPlans = actionPlanner.CreatePlansForGoal(goal, planningMemories, languageModel, scratchMemory);
                        newPlans.AddRange(goalPlans);
                    }
                }
                
                // 基于习惯生成计划
                if (scratchMemory != null && scratchMemory.habits.Count > 0)
                {
                    var habitPlans = actionPlanner.CreatePlansForHabits(scratchMemory.habits, scratchMemory);
                    newPlans.AddRange(habitPlans);
                }
                
                // 基于社交需求生成计划
                var socialPlans = GenerateSocialPlans(planningMemories, scratchMemory);
                newPlans.AddRange(socialPlans);
                
                // 基于环境机会生成计划
                var opportunityPlans = GenerateOpportunityPlans(planningMemories, scratchMemory);
                newPlans.AddRange(opportunityPlans);
                
                // 限制计划数量
                newPlans = newPlans.OrderByDescending(p => p.priority).Take(maxActivePlans).ToList();
                
                foreach (var plan in newPlans)
                {
                    totalPlansCreated++;
                    planTypeStats[plan.action] = planTypeStats.GetValueOrDefault(plan.action, 0) + 1;
                    OnPlanCreated?.Invoke(plan);
                }
                
                if (enablePlanningLogging)
                {
                    Debug.Log($"[PlanningSystem] Generated {newPlans.Count} new plans");
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"[PlanningSystem] Error generating new plans: {ex.Message}");
            }
            
            return newPlans;
        }
        
        /// <summary>
        /// 生成社交计划
        /// </summary>
        private List<PlanItem> GenerateSocialPlans(List<MemoryNode> memories, ScratchMemory scratchMemory)
        {
            var socialPlans = new List<PlanItem>();
            
            try
            {
                if (scratchMemory == null) return socialPlans;
                
                // 基于最近对话伙伴生成跟进计划
                foreach (var partner in scratchMemory.recentConversationPartners.Take(2))
                {
                    if (scratchMemory.relationshipStates.TryGetValue(partner, out var relationship) && relationship > 0.3f)
                    {
                        var socialPlan = new PlanItem
                        {
                            description = $"Follow up conversation with {partner}",
                            action = "social_interaction",
                            targetLocation = scratchMemory.currentLocation, // 简化：使用当前位置
                            locationName = scratchMemory.currentLocationName,
                            scheduledTime = DateTime.Now.AddMinutes(UnityEngine.Random.Range(30, 120)),
                            estimatedDuration = TimeSpan.FromMinutes(15),
                            priority = 6,
                            motivation = $"Maintain relationship with {partner}"
                        };
                        
                        socialPlan.involvedAgents.Add(partner);
                        socialPlans.Add(socialPlan);
                    }
                }
                
                // 基于社交需求生成新的社交计划
                if (scratchMemory.socialBattery > 0.7f && scratchMemory.recentConversationPartners.Count < 3)
                {
                    var networkingPlan = new PlanItem
                    {
                        description = "Meet new people and socialize",
                        action = "networking",
                        targetLocation = scratchMemory.currentLocation,
                        locationName = "social area",
                        scheduledTime = DateTime.Now.AddMinutes(UnityEngine.Random.Range(60, 180)),
                        estimatedDuration = TimeSpan.FromMinutes(30),
                        priority = 5,
                        motivation = "Expand social network"
                    };
                    
                    socialPlans.Add(networkingPlan);
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"[PlanningSystem] Error generating social plans: {ex.Message}");
            }
            
            return socialPlans;
        }
        
        /// <summary>
        /// 生成机会计划
        /// </summary>
        private List<PlanItem> GenerateOpportunityPlans(List<MemoryNode> memories, ScratchMemory scratchMemory)
        {
            var opportunityPlans = new List<PlanItem>();
            
            try
            {
                // 基于最近观察到的环境变化生成机会计划
                var recentObservations = memories
                    .Where(m => m.type == MemoryType.Observation && (DateTime.Now - m.createdTime).TotalHours <= 2)
                    .OrderByDescending(m => m.poignancy)
                    .Take(5);
                
                foreach (var observation in recentObservations)
                {
                    if (observation.poignancy >= 6) // 只考虑重要的观察
                    {
                        var opportunityPlan = actionPlanner.CreateOpportunityPlan(observation, scratchMemory);
                        if (opportunityPlan != null)
                        {
                            opportunityPlans.Add(opportunityPlan);
                        }
                    }
                }
                
                // 基于位置机会生成计划
                if (scratchMemory != null && !string.IsNullOrEmpty(scratchMemory.currentLocationName))
                {
                    var locationPlan = actionPlanner.CreateLocationBasedPlan(scratchMemory.currentLocationName, scratchMemory);
                    if (locationPlan != null)
                    {
                        opportunityPlans.Add(locationPlan);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"[PlanningSystem] Error generating opportunity plans: {ex.Message}");
            }
            
            return opportunityPlans;
        }
        
        /// <summary>
        /// 收集规划相关记忆
        /// </summary>
        private List<MemoryNode> CollectPlanningMemories(ScratchMemory scratchMemory)
        {
            var planningMemories = new List<MemoryNode>();
            
            try
            {
                if (retrievalEngine == null) return planningMemories;
                
                // 检索与目标相关的记忆
                if (scratchMemory != null && scratchMemory.goals.Count > 0)
                {
                    foreach (var goal in scratchMemory.goals.Take(3))
                    {
                        var goalMemories = retrievalEngine.RetrieveForPlanning(goal, scratchMemory.currentLocation, scratchMemory.agentName);
                        planningMemories.AddRange(goalMemories);
                    }
                }
                
                // 检索最近的高重要性记忆
                var recentImportantMemories = memorySystem.AssociativeMemory.GetRecentMemories(TimeSpan.FromHours(6), 10)
                    .Where(m => m.poignancy >= 6);
                planningMemories.AddRange(recentImportantMemories);
                
                // 检索计划相关记忆
                var planMemories = memorySystem.AssociativeMemory.GetMemoriesByType(MemoryType.Plan, 5);
                planningMemories.AddRange(planMemories);
                
                // 去重
                planningMemories = planningMemories.GroupBy(m => m.nodeId).Select(g => g.First()).ToList();
            }
            catch (Exception ex)
            {
                Debug.LogError($"[PlanningSystem] Error collecting planning memories: {ex.Message}");
            }
            
            return planningMemories;
        }
        
        /// <summary>
        /// 评估当前计划
        /// </summary>
        private void EvaluateCurrentPlans()
        {
            try
            {
                var plansToRemove = new List<PlanItem>();
                
                foreach (var plan in currentPlans.ToList())
                {
                    // 检查过期计划
                    if (plan.scheduledTime.AddMinutes(30) < DateTime.Now && plan.status == PlanStatus.Planned)
                    {
                        plan.Cancel("expired");
                        plansToRemove.Add(plan);
                        totalPlansCancelled++;
                        OnPlanCancelled?.Invoke(plan);
                    }
                    
                    // 检查完成的计划
                    if (plan.status == PlanStatus.Completed || plan.status == PlanStatus.Cancelled)
                    {
                        plansToRemove.Add(plan);
                        
                        if (plan.status == PlanStatus.Completed)
                        {
                            totalPlansCompleted++;
                            // 存储计划完成记忆
                            memorySystem.StorePlan($"Completed: {plan.description}", DateTime.Now, plan.targetLocation, plan.locationName);
                        }
                    }
                }
                
                // 移除已处理的计划
                foreach (var plan in plansToRemove)
                {
                    currentPlans.Remove(plan);
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"[PlanningSystem] Error evaluating current plans: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 整合新计划
        /// </summary>
        private void IntegrateNewPlans(List<PlanItem> newPlans)
        {
            try
            {
                foreach (var newPlan in newPlans)
                {
                    // 检查冲突
                    if (!HasScheduleConflict(newPlan))
                    {
                        currentPlans.Add(newPlan);
                    }
                    else
                    {
                        // 尝试调整时间
                        var adjustedPlan = AdjustPlanTiming(newPlan);
                        if (adjustedPlan != null && !HasScheduleConflict(adjustedPlan))
                        {
                            currentPlans.Add(adjustedPlan);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"[PlanningSystem] Error integrating new plans: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 检查计划冲突
        /// </summary>
        private bool HasScheduleConflict(PlanItem newPlan)
        {
            foreach (var existingPlan in currentPlans)
            {
                if (existingPlan.status == PlanStatus.Planned || existingPlan.status == PlanStatus.InProgress)
                {
                    var existingStart = existingPlan.scheduledTime;
                    var existingEnd = existingPlan.scheduledTime.Add(existingPlan.estimatedDuration);
                    var newStart = newPlan.scheduledTime;
                    var newEnd = newPlan.scheduledTime.Add(newPlan.estimatedDuration);
                    
                    // 检查时间重叠
                    if (newStart < existingEnd && newEnd > existingStart)
                    {
                        return true;
                    }
                }
            }
            
            return false;
        }
        
        /// <summary>
        /// 调整计划时间
        /// </summary>
        private PlanItem AdjustPlanTiming(PlanItem plan)
        {
            try
            {
                var adjustedPlan = new PlanItem
                {
                    planId = System.Guid.NewGuid().ToString(),
                    description = plan.description,
                    action = plan.action,
                    targetLocation = plan.targetLocation,
                    locationName = plan.locationName,
                    estimatedDuration = plan.estimatedDuration,
                    priority = plan.priority,
                    motivation = plan.motivation,
                    isInterruptible = plan.isInterruptible,
                    involvedAgents = new List<string>(plan.involvedAgents),
                    requiredObjects = new List<string>(plan.requiredObjects)
                };
                
                // 尝试向后调整30分钟
                adjustedPlan.scheduledTime = plan.scheduledTime.AddMinutes(30);
                
                return adjustedPlan;
            }
            catch (Exception ex)
            {
                Debug.LogError($"[PlanningSystem] Error adjusting plan timing: {ex.Message}");
                return null;
            }
        }
        
        /// <summary>
        /// 优化计划顺序
        /// </summary>
        private void OptimizePlanOrder()
        {
            try
            {
                currentPlans = currentPlans
                    .OrderBy(p => p.scheduledTime)
                    .ThenByDescending(p => p.priority)
                    .ToList();
            }
            catch (Exception ex)
            {
                Debug.LogError($"[PlanningSystem] Error optimizing plan order: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 启动排队的计划
        /// </summary>
        private void StartQueuedPlans()
        {
            try
            {
                var currentTime = DateTime.Now;
                var plansToStart = currentPlans
                    .Where(p => p.status == PlanStatus.Planned && p.scheduledTime <= currentTime && p.CanExecute())
                    .Take(1) // 一次只启动一个计划
                    .ToList();
                
                foreach (var plan in plansToStart)
                {
                    plan.StartExecution();
                    OnPlanStarted?.Invoke(plan);
                    
                    if (enablePlanningLogging)
                    {
                        Debug.Log($"[PlanningSystem] Started plan: {plan.description}");
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"[PlanningSystem] Error starting queued plans: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 更新计划状态
        /// </summary>
        private void UpdatePlanStatus(PlanItem plan)
        {
            try
            {
                if (plan.status == PlanStatus.InProgress)
                {
                    // 检查计划是否应该完成
                    if (plan.actualStartTime.HasValue)
                    {
                        var elapsed = DateTime.Now - plan.actualStartTime.Value;
                        if (elapsed >= plan.estimatedDuration)
                        {
                            plan.Complete();
                            OnPlanCompleted?.Invoke(plan);
                            
                            if (enablePlanningLogging)
                            {
                                Debug.Log($"[PlanningSystem] Completed plan: {plan.description}");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"[PlanningSystem] Error updating plan status: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 生成初始日程安排
        /// </summary>
        private void GenerateInitialDailySchedule()
        {
            try
            {
                dailySchedule.Clear();
                
                // 生成基础的日常活动计划
                var basicActivities = new[]
                {
                    new { Time = 7, Action = "wake_up", Duration = 30, Priority = 5 },
                    new { Time = 8, Action = "breakfast", Duration = 30, Priority = 6 },
                    new { Time = 9, Action = "morning_routine", Duration = 60, Priority = 5 },
                    new { Time = 12, Action = "lunch", Duration = 45, Priority = 6 },
                    new { Time = 14, Action = "afternoon_activities", Duration = 120, Priority = 4 },
                    new { Time = 18, Action = "dinner", Duration = 60, Priority = 6 },
                    new { Time = 20, Action = "evening_relaxation", Duration = 90, Priority = 4 },
                    new { Time = 22, Action = "prepare_for_sleep", Duration = 30, Priority = 5 }
                };
                
                var today = DateTime.Today;
                
                foreach (var activity in basicActivities)
                {
                    var scheduledTime = today.AddHours(activity.Time);
                    if (scheduledTime > DateTime.Now) // 只添加未来的活动
                    {
                        var dailyPlan = new PlanItem
                        {
                            description = $"Daily activity: {activity.Action.Replace("_", " ")}",
                            action = activity.Action,
                            scheduledTime = scheduledTime,
                            estimatedDuration = TimeSpan.FromMinutes(activity.Duration),
                            priority = activity.Priority,
                            isInterruptible = activity.Action != "sleep" && activity.Action != "breakfast",
                            motivation = "Daily routine maintenance"
                        };
                        
                        dailySchedule.Add(dailyPlan);
                    }
                }
                
                OnDailyScheduleUpdated?.Invoke(dailySchedule);
                
                if (enablePlanningLogging)
                {
                    Debug.Log($"[PlanningSystem] Generated initial daily schedule with {dailySchedule.Count} activities");
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"[PlanningSystem] Error generating initial daily schedule: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 获取当前活动计划
        /// </summary>
        public PlanItem GetCurrentPlan()
        {
            return currentPlans.FirstOrDefault(p => p.status == PlanStatus.InProgress);
        }
        
        /// <summary>
        /// 获取下一个计划
        /// </summary>
        public PlanItem GetNextPlan()
        {
            return currentPlans
                .Where(p => p.status == PlanStatus.Planned)
                .OrderBy(p => p.scheduledTime)
                .FirstOrDefault();
        }
        
        /// <summary>
        /// 手动添加计划
        /// </summary>
        public void AddPlan(PlanItem plan)
        {
            if (plan != null && !HasScheduleConflict(plan))
            {
                currentPlans.Add(plan);
                totalPlansCreated++;
                OnPlanCreated?.Invoke(plan);
            }
        }
        
        /// <summary>
        /// 取消计划
        /// </summary>
        public void CancelPlan(string planId, string reason = "manually cancelled")
        {
            var plan = currentPlans.FirstOrDefault(p => p.planId == planId);
            if (plan != null)
            {
                plan.Cancel(reason);
                totalPlansCancelled++;
                OnPlanCancelled?.Invoke(plan);
            }
        }
        
        /// <summary>
        /// 获取所有当前计划
        /// </summary>
        public List<PlanItem> GetAllCurrentPlans()
        {
            return new List<PlanItem>(currentPlans);
        }
        
        /// <summary>
        /// 获取计划统计信息
        /// </summary>
        public string GetPlanningStats()
        {
            var activePlans = currentPlans.Count(p => p.status == PlanStatus.InProgress);
            var queuedPlans = currentPlans.Count(p => p.status == PlanStatus.Planned);
            
            var stats = $"Active Plans: {activePlans}, Queued Plans: {queuedPlans}\n";
            stats += $"Total Created: {totalPlansCreated}, Completed: {totalPlansCompleted}, Cancelled: {totalPlansCancelled}\n";
            stats += $"Daily Schedule Items: {dailySchedule.Count}\n";
            
            if (planTypeStats.Count > 0)
            {
                stats += "Plan Types:\n";
                foreach (var kvp in planTypeStats.OrderByDescending(x => x.Value))
                {
                    stats += $"  {kvp.Key}: {kvp.Value}\n";
                }
            }
            
            return stats;
        }
        
        /// <summary>
        /// 设置计划参数
        /// </summary>
        public void SetPlanningParameters(int maxDaily, int maxActive, float interval)
        {
            maxDailyPlans = maxDaily;
            maxActivePlans = maxActive;
            planningInterval = interval;
        }
        
        /// <summary>
        /// 重置计划统计
        /// </summary>
        public void ResetPlanningStats()
        {
            totalPlansCreated = 0;
            totalPlansCompleted = 0;
            totalPlansCancelled = 0;
            planTypeStats.Clear();
        }
        
        /// <summary>
        /// 检查是否正在规划
        /// </summary>
        public bool IsPlanningInProgress()
        {
            return isPlanningInProgress;
        }
    }
}